const gulp = require("gulp");
const gutil = require("gulp-util");
const sourcemaps = require("gulp-sourcemaps");

gulp.task("webpack", callback => {
    const webpack = require("webpack");
    const config = require("./webpack.config.js");
    webpack(config, (err, stats) => {
        if (err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString());
        callback();
    });
});

gulp.task("less", callback => {
    const less = require("gulp-less");

    return gulp.src("./less/**/*.less")
        .pipe(sourcemaps.init())
        .pipe(less())
        .pipe(sourcemaps.write("../css", {
            sourceRoot: "../app/less",
            sourceMappingURL: file => `${file.relative}.map`
        }))
        .pipe(gulp.dest("../css"));
});

gulp.task("build", ["webpack", "less"]);

gulp.task("watch", () => {
    gulp.watch("./src/**/*.js", { interval: 1000 }, ["webpack"]);
    gulp.watch("./less/**/*.less", { interval: 300 }, ["less"]);
});

gulp.task("default", ["watch", "build"]);
